
package com.yimixian.app.fragment;

import com.squareup.picasso.Picasso;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.EventBusDomain.HomeDataLocatedStatus;
import com.yimixian.app.EventBusDomain.PlusMinusIconMessage;
import com.yimixian.app.EventBusDomain.ShowAdSelectChange;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.activity.YMXMainActivity;
import com.yimixian.app.adapter.GoodsItemListViewAdapter;
import com.yimixian.app.address.ChooseAddressOrStoreActivity;
import com.yimixian.app.address.ShowAddressesActivity;
import com.yimixian.app.address.SwitchAddressActivity;
import com.yimixian.app.cart.CartManager;
import com.yimixian.app.cart.GoodsItemPresenter;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.SharePreferenceKeys;
import com.yimixian.app.common.StatConstants;
import com.yimixian.app.common.UMengConstants;
import com.yimixian.app.common.WebViewActivity;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.goods.GoodsView;
import com.yimixian.app.goods.SectionItemView;
import com.yimixian.app.model.Address;
import com.yimixian.app.model.CartUpdate;
import com.yimixian.app.model.Category;
import com.yimixian.app.model.GoodsItem;
import com.yimixian.app.model.Section;
import com.yimixian.app.net.HttpApi;
import com.yimixian.app.receiver.ButtonClickTransHelper;
import com.yimixian.app.rest.api.CartUpdateAPI;
import com.yimixian.app.rest.api.CategoryAPI;
import com.yimixian.app.rest.api.CategoryGoodsAPI;
import com.yimixian.app.search.SearchActivity;
import com.yimixian.app.ui.ParabolaView;
import com.yimixian.app.util.DateUtil;
import com.yimixian.app.util.PaoWuXianAnimTool;
import com.yimixian.app.util.PaoWuXianAnimator;
import com.yimixian.app.util.ServiceUtils;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;
import com.ymx.sdk.widget.PullToRefreshView.PullToRefreshBase;
import com.ymx.sdk.widget.PullToRefreshView.PullToRefreshListView;

import de.greenrobot.event.EventBus;

import org.json.JSONException;
import org.json.JSONObject;

import retrofit.client.Response;
import rx.Subscription;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import java.util.HashMap;
import java.util.Map;

public class CategoryFragment extends DialogGoodDetailFragment implements
        GoodsItemPresenter.OnPlusButtonClickListener,
        GoodsItemPresenter.OnGoodsQuantityChangedListener,
        PullToRefreshBase.OnRefreshListener2<ListView>, ServiceUtils.CountDownDataListener {

    private static final int EMPTY_SECTION_ID = -1;
    public static final int SAVED_STORE_TYPE_ADDRESS = 0;
    public static final int SAVED_STORE_TYPE_PICK_UP = 1;
    public static final String IS_NEED_FETCH_DATA = "is_need_fetch_data";
    public static final String NEED_FETCH_DATA = "need_fetch_data";

    public static String mCurrentTab = "";

    @InjectView(R.id.ll_top_bar)
    LinearLayout mTopBar;
    @InjectView(R.id.section_list)
    ListView mSectionListView;
    @InjectView(R.id.home_goods_list)
    PullToRefreshListView mGoodsItemListView;
    @InjectView(R.id.education_img)
    ImageView mEducationImage;
    @InjectView(R.id.address_text)
    TextView mAddressText;
    @InjectView(R.id.fetch_method_text)
    TextView mFetchMethodText;
    @InjectView(R.id.user_icon)
    ImageView mUserIcon;
    @InjectView(R.id.iv_address)
    ImageView iv_address;
    @InjectView(R.id.iv_right_arrow)
    ImageView iv_right_arrow;
    @InjectView(R.id.main_frame)
    FrameLayout mMainFrame;
    @InjectView(R.id.pull_message_frame)
    FrameLayout mPullMessageFrame;
    @InjectView(R.id.content_frame)
    FrameLayout mContentFrame;
    @InjectView(R.id.loading_view)
    LinearLayout mLoadingView;
    @InjectView(R.id.cannot_deliver_view)
    LinearLayout mCannotDeliverView;
    @InjectView(R.id.locating_failed_view)
    LinearLayout mLocatingFailedView;
    @InjectView(R.id.show_delivery_zone_button)
    TextView mShowDeliveryZoneButton;
    @InjectView(R.id.cannot_deliver_text)
    TextView mCannotDeliverText;
    @InjectView(R.id.loading_text)
    TextView mLoadingText;
    @InjectView(R.id.iv_send)
    ImageView iv_send;

    private SharedPreferences mSharedPreferences;
    private CartManager mCartManager;
    private int mSelectedSectionId;
    private Address mCurrentAddress;
    private Handler mHandler = new Handler();
    private boolean mIsCreated = false;
    private View mRootView;
    private ButtonClickTransHelper mButtonClickTransHelper;
    private CategoryAPI mCategoryAPI;
    private CategoryGoodsAPI mCategoryGoodsAPI;
    private Category mCategory;
    private int mCategoryId = 0;
    private int storeId = 0;
    private boolean isNeedGetCart = true;
    private PlusMinusIconMessage mPlusMinusIconMessage;
    private GoodsItemListViewAdapter mGoodsItemListViewAdapter;
    private boolean mIsAddressChanged = false;
    private int mCurrentGoodsItemId;
    private boolean isRefreshGoods;
    private Dialog tipDialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        DateUtil.setCityUMeng(null, UMengConstants.NEW_CATEGORY_PV);
        if (mIsCreated && mRootView != null) {
            return mRootView;
        }
        setupMemberVariables();
        mRootView = initView(inflater);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().registerSticky(this);
        }
        // fetchData();
        mIsCreated = true;
        if(savedInstanceState != null) {
            String isNeedFetchData = savedInstanceState.getString(IS_NEED_FETCH_DATA);
            if(!TextUtils.isEmpty(isNeedFetchData) && NEED_FETCH_DATA.equals(isNeedFetchData)) {
                fetchData();
            }
        }
        if (getActivity() instanceof YMXMainActivity) {
            // this.mCartTab = (CartRadioButton) ((YMXMainActivity)
            // getActivity()).mCartTab;
            CartManager.getInstance().setCartQuantityTextView(
                    ((YMXMainActivity) getActivity()).mCartContent);
        }

        return mRootView;
    }

    @Override
    public void initRequestAPI(String requestKeys) {
        if (requestKeys != null && CartUpdateAPI.CART_UPDATE_API.equals(requestKeys)
                && mCartUpdateAPI == null) {
            initCartUpdateAPI();
        } else if (requestKeys != null && CategoryAPI.CATEGORY_GET.equals(requestKeys)) {
            UiUtils.setLastFlushTime(this);
            mCategoryAPI = new CategoryAPI(this);
            mCategoryAPI.categoryGet();
        }else if (requestKeys != null && CategoryGoodsAPI.CATEGORY_GOODS_GET.equals(requestKeys)){
            mCategoryGoodsAPI = new CategoryGoodsAPI(mSelectedSectionId, storeId, this);
            mCategoryGoodsAPI.categoryGoodsGet();
        }
    }

    @Override
    public void onHttpSuccess(String url, JSONObject responseJson) {
        if (mGoodsItemListView != null) mGoodsItemListView.onRefreshComplete();
        hidePopupWindow();
        hideDialog();
        if (mCartUpdateAPI != null) {
            if (url.contains(mCartUpdateAPI.CART_UPDATE)) {
                CartUpdate cartUpdate = mCartUpdateAPI.parseJson(responseJson);
                CartManager.getInstance().updateCartGoods(cartUpdate, mPlusMinusIcon);
            }
            if (url.contains(CartUpdateAPI.CART_GET)) {
                CartUpdate cartUpdate = mCartUpdateAPI.parseJson(responseJson);
                CartManager.getInstance().updateCartGoods(cartUpdate);
                if (mGoodsItemListViewAdapter != null) {
                    mGoodsItemListViewAdapter.notifyDataSetChanged();
                }
                if (mPlusMinusIconMessage != null
                        && mPlusMinusIconMessage.message.contains("/IsFisrt")
                        && mPlusMinusIconMessage.icon != null) {
                    mPlusMinusIconMessage.message = mPlusMinusIconMessage.icon.mCurrentButtonState;
                    if(mPlusMinusIconMessage != null && mPlusMinusIconMessage.icon != null && mPlusMinusIconMessage.icon.mGoodsItem != null) {
                        if(mCurrentGoodsItemId == mPlusMinusIconMessage.icon.mGoodsItem.id) {
                            EventBus.getDefault().post(mPlusMinusIconMessage);
                        }
                    }
                    EventBus.getDefault().removeStickyEvent(mPlusMinusIconMessage);
                }
            }
            if (mPlusMinusIcon != null) {
                mPlusMinusIcon.setButtonCanClick(true);
            }
            UiUtils.updateCartDescription(getActivity(), Constants.PageType.CATEGORY);
        }
        if (url.contains(CategoryAPI.CATEGORY_GET) && url.contains("goods")){//获取每个分类下面的商品列表
            if (mCategoryGoodsAPI != null){
                Category category = mCategoryGoodsAPI.parseJson(responseJson);
                if (category != null) {
                    mCategory.banners = category.banners;
                    mCategory.goods = category.goods;
                    //拉取分类下的数据
                    onInitGoodsData();
                }
            }
        }else{//获取分类
            if (mCategoryAPI != null) {
                if (url.contains(CategoryAPI.CATEGORY_GET)) {
                    Category category = mCategoryAPI.parseJson(responseJson);
                    if (category != null) {
                        mCategory = category;
                        /*if (mCategory.categories != null &&
                                mCategory.categories.size() > 0){*/
                            initCategorySections(category);
                        /*    //                        onStoreFetched();
                        }*/
                    }
                }
            }
        }
    }

    @Override
    public void getRawResponse(String url, Response response) {
        super.getRawResponse(url, response);
        ServiceUtils.setTime(response);
    }

    @Override
    public void OnHttpFailure(String url, String errorMessage, boolean errorFromUs) {
        if (mGoodsItemListView != null) mGoodsItemListView.onRefreshComplete();
        if (mPlusMinusIcon != null) {
            mPlusMinusIcon.setButtonCanClick(true);
        }
        if(mLoadingView != null) {
            mLoadingView.setVisibility(View.GONE);
        }
        hidePopupWindow();
        hideDialog();
    }

    @Override
    public void fetchDataFromNetwork(String key) {
        initRequestAPI(key);
    }

    private void setupMemberVariables() {
        mSharedPreferences = getActivity().getSharedPreferences(Constants.SHARED_PREFS_NAME,
                Context.MODE_PRIVATE);
        mCartManager = CartManager.getInstance();
        mSelectedSectionId = EMPTY_SECTION_ID;
    }

    private void fetchData() {
        showLoadingView(getString(R.string.loading));
        getJiShiSonData(true);
    }


    private void showLoadingView(String loadingText) {
        if (mContentFrame == null)
            return;
        mContentFrame.setVisibility(View.INVISIBLE);
        mLoadingView.setVisibility(View.VISIBLE);
        mLoadingText.setText(loadingText);
        mCannotDeliverView.setVisibility(View.GONE);
        mLocatingFailedView.setVisibility(View.GONE);
    }

    private void fetchNormalStore(boolean showLoadingView) {
        Address address = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        if (showLoadingView) {
            if (isAdded()) {
                showLoadingView(getString(R.string.loading));
            }
        }
        mCurrentAddress = address;
        if (mCurrentAddress != null) {
            // 区分自提还是配送
            mFetchMethodText.setText(mCurrentAddress.isPickup ? getString(R.string.pick_up_self)
                    : getString(R.string.send_to));
            setmAddressText(address);
            mAddressText.setVisibility(View.VISIBLE);
//            iv_address.setVisibility(View.VISIBLE);
//            mFetchMethodText.setVisibility(View.GONE);
        }

        // 拉取分类页面的数据
        fetchData(true, CategoryAPI.CATEGORY_GET);
    }

    private void setIcon(String result){
        JSONObject json = null;
        try {
            json = new JSONObject(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (json != null) {
            String type = json.optString("delivery_img");
            String tip = "";
            iv_send.setVisibility(View.VISIBLE);
            iv_address.setVisibility(View.VISIBLE);
            mFetchMethodText.setVisibility(View.GONE);
            iv_right_arrow.setVisibility(View.VISIBLE);
            if (Strings.isNullOrEmpty(type)) {//配送至
                iv_send.setVisibility(View.GONE);
                mFetchMethodText.setVisibility(View.VISIBLE);
                mFetchMethodText.setText(UiUtils.getSafeActivity(CategoryFragment.this).getResources()
                        .getString(R.string.send_to));
                iv_address.setVisibility(View.GONE);
            } else if ("delivery_zt".equals(type)) {//自提
                iv_send.setImageResource(R.drawable.icon_address_self);
                if (Strings.isNullOrEmpty(mCurrentAddress.poiName)) {
                    tip = "该地区支持自提服务，下单后请您于次日到" + mCurrentAddress.poiAddress + "领取您的订单";
                } else {
                    tip = "该地区支持自提服务，下单后请您于次日到" + mCurrentAddress.poiName + "领取您的订单";
                }
            } else if ("delivery_jss_crd".equals(type)) {//及时送(59分钟达)和次日达
                iv_send.setImageResource(R.drawable.icon_address_59_and_next);
                tip = "该地区支持次日达及59分达服务。59分达商品将于您下单后59分内送达，次日达商品将于您下单后次日送达";
            } else if ("delivery_jss".equals(type)) {//及时送(59分钟达)
                iv_send.setImageResource(R.drawable.icon_address_59);
                tip = "该地区支持59分达服务，您的订单将于下单后59分内送达";
            } else if ("delivery_crd".equals(type)) {//次日达
                iv_send.setImageResource(R.drawable.icon_address_next);
                tip = "该地区支持次日达服务，您的订单将于下单后次日送达";
            } else if (type != null && type.startsWith("http")) {
                Picasso.with(getContext()).load(type).into(iv_send);
            }
            if (!Strings.isNullOrEmpty(tip)) {
                final String message = tip;
                iv_send.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        tipDialog = UiUtils.showOKDialog(getContext(), message, "知道了", new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                if (tipDialog != null)
//                                    tipDialog.dismiss();
//                            }
//                        });
                        mTopBar.performClick();
                    }
                });
                TranslateAnimation trans = new TranslateAnimation(
                        Animation.RELATIVE_TO_SELF, -1.0f,Animation.RELATIVE_TO_SELF, 0f,
                        Animation.RELATIVE_TO_SELF, 0f,Animation.RELATIVE_TO_SELF, 0f);
                trans.setDuration(300);
                trans.setStartOffset(300);
                iv_send.startAnimation(trans);
            }
        }
    }

    private void setmAddressText(Address address){
        String text = "";
        //无poi点, 手动输入显示的地址
        if(Strings.isNullOrEmpty(address.poiName)){
            if(!Strings.isNullOrEmpty(address.poiAddress)){
                if(address.poiAddress.length() <= Constants.HOME_TITLE_MAX_LENGTH){
                    text = address.poiAddress;
                }else{
                    text = address.poiAddress.substring(0, Constants.HOME_TITLE_MAX_LENGTH) + "...";
                }
            }
        }else{
            if(!Strings.isNullOrEmpty(address.poiName)){
                if(address.poiName.length() <= Constants.HOME_TITLE_MAX_LENGTH){
                    text = address.poiName;
                }else{
                    text = address.poiName.substring(0, Constants.HOME_TITLE_MAX_LENGTH) + "...";
                }
            }
        }
        mAddressText.setText(text);
    }

    private void getJiShiSonData(final boolean showLoading) {
        Address address = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        if(address != null){
            mCurrentAddress = address;
            setmAddressText(address);
            mAddressText.setVisibility(View.VISIBLE);
            iv_address.setVisibility(View.VISIBLE);
            iv_right_arrow.setVisibility(View.VISIBLE);
            mFetchMethodText.setVisibility(View.GONE);
            iv_send.setVisibility(View.GONE);
            getJiShiSonData(mCurrentAddress.longitude, mCurrentAddress.latitude, showLoading);
        }
    }

    private void getJiShiSonData(String longitude, String latitude, final boolean showLoading) {
        if(mCurrentAddress != null && mCurrentAddress.id != 0){
            getJiShiSonDataNotPOI(mCurrentAddress.id + "", showLoading);
            return;
        }
        if (showLoading) {
            if (isAdded()) {
                showLoadingView(getString(R.string.loading));
            }
        }
        iv_send.setVisibility(View.GONE);
        Map<String, String> map = new HashMap<>();
        map.put("longitude", longitude);
        map.put("latitude", latitude);
        map.put("coord_system", Constants.BAIDU_COORD_SYSTEM);
        HttpApi.startGetRequest("/stores/store_info", map, new HttpApi.RequestCallBack() {
            @Override
            public void requestSuccess(String result) {
                setIcon(result);
            }

            @Override
            public void requestError() {

            }

            @Override
            public void alwaysDo() {
                fetchNormalStore(showLoading);
            }
        });
    }

    private void getJiShiSonDataNotPOI(String storeId, final boolean showLoading) {
        if (showLoading) {
            if (isAdded()) {
                showLoadingView(getString(R.string.loading));
            }
        }
        iv_send.setVisibility(View.GONE);
        Map<String, String> map = new HashMap<>();
        map.put("address_id", storeId);
        HttpApi.startGetRequest("/stores/store_info", map, new HttpApi.RequestCallBack() {
            @Override
            public void requestSuccess(String result) {
                setIcon(result);
            }

            @Override
            public void requestError() {

            }

            @Override
            public void alwaysDo() {
                fetchNormalStore(showLoading);
            }
        });
    }

    /**
     * 同步购物车数据
     */
    private void flushCartData() {
        if (isNeedGetCart && DataManager.getInstance().get(CacheKeys.TOKEN) != null) {
            getCartData();
            isNeedGetCart = false;
        }
    }

    /**
     * 获取购物车数据
     */
    private void getCartData() {
        fetchUpdateCartData();
        if (getActivity() != null) {
            showPopupWindow(getActivity(), R.id.popupwindow_container);
        }
        if (mCartUpdateAPI != null) {
            mCartUpdateAPI.getCartInfo();
        }
    }

    private void showFetchDataErrorUi() {
        DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case DialogInterface.BUTTON_NEUTRAL:
                        MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                                StatConstants.HOME_FETCH_DATA_ERROR_CLICK);
                        fetchData();
                        break;
                }
            }
        };

        if (isAdded()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
                    .setMessage(getString(R.string.network_error_try_again))
                    .setNeutralButton(getString(R.string.retry), dialogClickListener)
                    .setCancelable(false);
            UiUtils.showAlertDialog(builder);
        }
    }

    private void showLocatingFailedUi() {
        if (mLocatingFailedView == null) {
            return;
        }
        mLocatingFailedView.setVisibility(View.VISIBLE);
        mContentFrame.setVisibility(View.INVISIBLE);
        mLoadingView.setVisibility(View.GONE);
        mCannotDeliverView.setVisibility(View.GONE);
        mAddressText.setText(getString(R.string.manual_choose_address));
        mAddressText.setVisibility(View.VISIBLE);
        iv_address.setVisibility(View.VISIBLE);
        mFetchMethodText.setVisibility(View.GONE);
    }

    @Override
    public void onStart() {
        super.onStart();
        // fetchUser();
        // onGoodsQuantityChanged();
    }


    @Override
    public void onStop() {
        super.onStop();
        mGoodsItemListView.onRefreshComplete();
        // mRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString(IS_NEED_FETCH_DATA, NEED_FETCH_DATA);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onResume() {
        if (isRefreshGoods) {
            refreshGoodsListView();
            isRefreshGoods = false;
        }
        if (DataManager.getInstance().get(CacheKeys.TOKEN) == null) {
            mIsAddressChanged = true;
        }
        if(mIsAddressChanged) {
            reFreshData();
            mIsAddressChanged = false;
        }
        if (UiUtils.isNeedFlush(this)) {
            fetchData(true, CategoryAPI.CATEGORY_GET);
        } else {
            if (mCategory != null) {
                CartManager.getInstance().setSections(mCategory.goods);
                if (mGoodsItemListViewAdapter != null) {
                    mGoodsItemListViewAdapter.setGoodsViewModels(CartManager.getInstance().getViewModels(mCategory));
                }
            }
        }
        if (isAdded()) UiUtils.updateCartDescription(getActivity(), Constants.PageType.CATEGORY);
        super.onResume();
    }

    @Override
    public void onDestroy() {
        if (mShowDialogReceiver != null && mShowDialogReceiver != null
                && mButtonClickTransHelper != null) {
            mButtonClickTransHelper.unRegistGetTypeGiftBroadCastReceiver(mShowDialogReceiver);
            mButtonClickTransHelper = null;
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        super.onDetach();
    }

    @Override
    public void onDestroyView() {
        mPlusMinusIconMessage = null;
        super.onDestroyView();
    }

    private View initView(LayoutInflater inflater) {
        View rootView = inflater.inflate(R.layout.main_activity, null);
        mDialogView = (ViewGroup) rootView.findViewById(R.id.fl_dialog_container);
        RelativeLayout search = (RelativeLayout) rootView.findViewById(R.id.rl_search);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(UiUtils.isFastDoubleClick()) {
                    return ;
                }
                if(isAdded()) {
                    MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                            UMengConstants.NEW_CATEGORY_SEARCH_BTN);
                    Intent intent = SearchActivity.buildIntent(getActivity());
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.slide_in_from_right,0);
                }
            }
        });

        ButterKnife.inject(this, rootView);

        View footerView = new View(getActivity());
        footerView.setEnabled(false);
        footerView.setVisibility(View.INVISIBLE);
        AbsListView.LayoutParams params = new AbsListView.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, 150);
        footerView.setLayoutParams(params);
        mGoodsItemListView.getRefreshableView().addFooterView(footerView);

        mButtonClickTransHelper = new ButtonClickTransHelper();
        mButtonClickTransHelper.registGetTypeGiftBroadCastReceiver(mShowDialogReceiver,
                new IntentFilter(Constants.STATE_HOMEFRAGMENT_BUTTON_BROADCAST));

        View view = new View(getActivity());
        view.setLayoutParams(new AbsListView.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                getResources().getDimensionPixelSize(R.dimen.bar_height)));
        mGoodsItemListView.setOnRefreshListener(this);
        return rootView;
    }

    // 下拉刷新
    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS) == null) {
                    // startLocatingCurrentAddress();
                    showLocatingFailedUi();
                } else {
                    fetchData(true, CategoryGoodsAPI.CATEGORY_GOODS_GET);
                }
            }
        }, 800);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
    }

    @OnClick({
            R.id.ll_top_bar
    })
    public void onAddressTextClicked() {

        if(UiUtils.isFastDoubleClick()) {
            return;
        }
        MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                StatConstants.HOME_ADDRESS_HEADER_CLICK);
        if(DataManager.getInstance().get(CacheKeys.TOKEN) == null && !"请手动选择收货地址".equals(mAddressText.getText().toString())){
            startActivityForResult(new Intent(getActivity(), SwitchAddressActivity.class), 0);
        }else{
            startActivityForResult(
                    new Intent(getActivity(), ChooseAddressOrStoreActivity.class).putExtra(
                            ShowAddressesActivity.EXTRA_MODE,
                            ShowAddressesActivity.LOCATE_ADDRESS_MODE),
                    Constants.PICK_ADDRESS_REQUEST_CODE);
        }

//        MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
//                StatConstants.HOME_ADDRESS_HEADER_CLICK);
//        startActivityForResult(
//                new Intent(getActivity(), ChooseAddressOrStoreActivity.class).putExtra(
//                        ShowAddressesActivity.EXTRA_MODE,
//                        ShowAddressesActivity.LOCATE_ADDRESS_MODE),
//                Constants.PICK_ADDRESS_REQUEST_CODE);
    }

    @Override
    public void onGoodsQuantityChanged() {
        for (int i = 0; i < mGoodsItemListView.getChildCount(); ++i) {
            View child = mGoodsItemListView.getChildAt(i);
            if (child instanceof GoodsView) {
                GoodsView goodsView = (GoodsView) child;
            }
        }
    }

    @Override
    public boolean checkGiftGoods(GoodsItem item) {
        if (item.typeGift == null) {
            return true;
        } else if (mCartManager.mHasFreebie) {
            mButtonClickTransHelper.sendButtonClickBroadCast(mCartManager.mCurrentState, 0);
            return false;
        } else if (item.typeGift.minTotalPrice > mCartManager.mTotalPrice) {
            mButtonClickTransHelper.sendButtonClickBroadCast(mCartManager.mCurrentState, 1,
                    item.typeGift.minTotalPrice);
            return false;
        }
        return true;
    }

    //初始化分类页面左侧分类
    public void initCategorySections(Category category){
        if (mCategory == null) {
            return;
        }
        storeId = mCategory.storeId;
//        CartManager.getInstance().saveStoreID(storeId);
        mGoodsItemListView.onRefreshComplete();
//        mAddressText.setVisibility(View.VISIBLE);
//        iv_address.setVisibility(View.VISIBLE);
//        mFetchMethodText.setVisibility(View.GONE);
        if (mCategory.categories.size() == 0) {
            mSelectedSectionId = EMPTY_SECTION_ID;
            if(!TextUtils.isEmpty(mCategory.cannotDeliverText))showCannotDeliverView();
            return;
        } else {
            mSelectedSectionId = mCategory.categories.get(0).id;
            mSectionListView.setAdapter(new SectionListViewAdapter());
            mContentFrame.setVisibility(View.VISIBLE);
            mLoadingView.setVisibility(View.GONE);
            mLocatingFailedView.setVisibility(View.GONE);
            mCannotDeliverView.setVisibility(View.GONE);
        }
        //拉取右侧数据
        if (isAdded()) {
            showPopupWindow(getActivity(), R.id.popupwindow_container);
        }
        fetchData(true, CategoryGoodsAPI.CATEGORY_GOODS_GET);
    }

    private void onInitGoodsData() {
        if (mCategory != null) ServiceUtils.infilterServiceData(getActivity(), mCategory.goods,
                Constants.ServicePageType.CATEGORYFRAGMENT);
        mCartManager.setSections(mCategory.goods);
        // 同步购物车
        flushCartData();
        refreshGoodsListView();
        sendAddressChangeFinshBroadcast();
    }

    private void showCannotDeliverView() {
        mContentFrame.setVisibility(View.INVISIBLE);
        mLoadingView.setVisibility(View.GONE);
        mLocatingFailedView.setVisibility(View.GONE);
        mCannotDeliverView.setVisibility(View.VISIBLE);
        iv_address.setVisibility(View.GONE);
        mFetchMethodText.setVisibility(View.VISIBLE);
        if (mCategory != null && !Strings.isNullOrEmpty(mCategory.cannotDeliverText)) {
            mCannotDeliverText.setText(mCategory.cannotDeliverText);
        }
        if (mCategory != null && Strings.isNullOrEmpty(mCategory.deliverZoneUrl)) {
            mShowDeliveryZoneButton.setVisibility(View.GONE);
        } else {
            mShowDeliveryZoneButton.setVisibility(View.VISIBLE);
            mShowDeliveryZoneButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MobclickAgent.onEvent(getActivity(), StatConstants.HOME_CANNOT_DELIVERY_CLICK);
                    Intent intent = new Intent(getActivity(), WebViewActivity.class);
                    intent.putExtra(WebViewActivity.EXTRA_URL, mCategory.deliverZoneUrl);
                    startActivity(intent);
                }
            });
        }
    }

    //右侧分类条目点击事件
    private void onSectionClicked(final SectionItemView view) {
        if (mSelectedSectionId == view.getSectionId()) {
            return;
        }

        Map<String, String> hashMap_ = new HashMap<>();
        hashMap_.put("ID", view.getSectionId() + "");
        DateUtil.setCityUMeng(hashMap_, UMengConstants.NEW_CATEGORY_PV_DETAIL);

        if (mGoodsItemListViewAdapter != null) {
            mGoodsItemListViewAdapter.removeAllList();
            mGoodsItemListViewAdapter.notifyDataSetChanged();
        }
        MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                StatConstants.HOME_LEFT_SECTION_FINISH_CLICK);
        SectionItemView currentSelectedView = findSectionItemView(mSelectedSectionId);
        if (currentSelectedView != null) {
            mSectionListView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mSectionListView.smoothScrollToPositionFromTop((int)view.getTag(), 0);
                }
            },300);
            currentSelectedView.setClicked(false);
            String titleName = currentSelectedView.getTextViewTitle();
            if (!TextUtils.isEmpty(titleName)) {
                mCurrentTab = titleName;
                Map<String, String> hashMap = new HashMap<String, String>();
                hashMap.put("categoryId", String.valueOf(mSelectedSectionId));
                MobclickAgent.onEvent(
                        SystemFramework.getInstance().getGlobalContext(),
                        UMengConstants.NEW_CATEGORY_LEFTTAB, hashMap);
            }
        }
        view.setClicked(true);
        mSelectedSectionId = view.getSectionId();
        mCategoryId = mSelectedSectionId;
        if (isAdded()) {
            showPopupWindow(getActivity(), R.id.popupwindow_container);
        }
        fetchData(true, CategoryGoodsAPI.CATEGORY_GOODS_GET);
    }

    private void refreshGoodsListView() {
        if (mCategory == null) {
            return;
        }
        if (mGoodsItemListView != null) {
            if (mSelectedSectionId != EMPTY_SECTION_ID && isAdded()) {
                mGoodsItemListViewAdapter = new GoodsItemListViewAdapter(
                        CartManager.getInstance().getViewModels(mCategory),
                        getActivity(), this, mCartManager, this);
                mGoodsItemListView.setAdapter(mGoodsItemListViewAdapter);
            }
            if (!isAdded()){
                isRefreshGoods = true;
            }
        }
    }

    private SectionItemView findSectionItemView(int sectionId) {
        for (int i = 0; i < mSectionListView.getChildCount(); ++i) {
            SectionItemView view = (SectionItemView) mSectionListView.getChildAt(i);
            if (view.getSectionId() == sectionId) {
                return view;
            }
        }

        return null;
    }

    @Override
    public void isNeedUpdate() {
        if (mGoodsItemListViewAdapter != null)
            mGoodsItemListViewAdapter.notifyDataSetChanged();
    }

    @Override
    public void isNeedUnbindService() {

    }

    private class SectionListViewAdapter extends BaseAdapter {

        private View.OnClickListener mClickListener=new View.OnClickListener(){
            @Override
            public void onClick(View v){
                onSectionClicked((SectionItemView)v);
            }
        };

        @Override
        public int getCount() {
            if (mCategory == null) {
                return 0;
            } else if (mCategory.categories == null) {
                return 0;
            } else {
                return mCategory.categories.size();
            }
        }

        @Override
        public Section getItem(int position) {
            return mCategory.categories.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = new SectionItemView(getActivity());
                convertView.setOnClickListener(mClickListener);
            }
            convertView.setTag(position);
            SectionItemView itemView = (SectionItemView) convertView;
            Section section = getItem(position);
            itemView.init(section.name, section.subTitle, section.id);
            itemView.setClicked(section.id == mSelectedSectionId);
            return itemView;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }
    }


    @Override
    public void onPlusButtonClick(View plusView, Point startPoint, Bitmap animBack) {

        ImageView mCartView = ((YMXMainActivity) getActivity()).getmCartView();
        PaoWuXianAnimTool.startAnim(getActivity(), plusView, mCartView, animBack, PaoWuXianAnimTool.DEFAULT_DURATION, new PaoWuXianAnimator.onPaoWuXianEndListener() {
            @Override
            public void onEnd() {
                if(getActivity() instanceof YMXMainActivity)
                    ((YMXMainActivity) getActivity()).initCartViewAnim(false);
            }
        });

        if(true)
            return;

        ParabolaView parabolaView = new ParabolaView(getActivity(), animBack);
        if (mMainFrame != null) {
            mMainFrame.addView(parabolaView);
        }
        parabolaView.setAnimListener(new ParabolaView.AnimListener() {
            @Override
            public void onEndAnim() {
                if(getActivity() instanceof YMXMainActivity)
                    ((YMXMainActivity) getActivity()).initCartViewAnim(false);
            }
        });
        parabolaView.startAnimation(mHandler, SharedPreferencesHelper.getCartViewLocation(),
                startPoint);
    }

    public void reFreshData() {
        Address noLoginAddress = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_NO_LOGIN_ADDRESS);
        if (SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS) == null
                && (noLoginAddress == null || noLoginAddress.id == -1)) {
            showLocatingFailedUi();
        } else {
            getJiShiSonData(true);
        }
    }

    public void sendAddressChangeFinshBroadcast() {
        SharedPreferencesHelper.setIsLodingData(false);
        Intent intent = new Intent(Constants.BROADCAST_RECEIVE_ADDRESS_CHANGE_FINISH);
        LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);

    }

    BroadcastReceiver mShowDialogReceiver=new BroadcastReceiver(){@Override public void onReceive(Context context,Intent intent){
        if(Constants.STATE_HOMEFRAGMENT_BUTTON_BROADCAST.equals(intent.getAction())){
            int state=intent.getExtras().getInt(Constants.GOOD_ID);
            if(state==0){showCountLimitDialog();
        }else{
            float price=intent.getExtras().getFloat(Constants.ITEM_GIGTTYPE_MIN_PRICE);showMoneyLimitDialog(price);
        }}}};

    // 地址管理页面 监听到地址改变更新首页内容
    public void onEventMainThread(ShowAdSelectChange event) {
        mSharedPreferences.edit().putBoolean(Constants.IS_LOADING_DATA, true).commit();
        showLoadingView(getString(R.string.loading));
        mCategoryId = 0;
        mIsAddressChanged = true;
        mSelectedSectionId = EMPTY_SECTION_ID;
        EventBus.getDefault().removeStickyEvent(event);
    }

    // 刷新ListView中的数据
    public void onEventMainThread(String message) {
        if (message != null) {
            // 刷新HomeFragment中商品列表
            if ((Constants.EVENT_BUS_HOME_FRAGMENT_REFRESH).equals(message)) {
                if (mGoodsItemListViewAdapter != null) {
                    mGoodsItemListViewAdapter.notifyDataSetChanged();
                    UiUtils.updateCartDescription(getActivity(), Constants.PageType.CATEGORY);
                }
                EventBus.getDefault().removeStickyEvent(message);
            }
            // 拉取商铺及购物车
            else if (Constants.EVENT_BUS_GET_CART.equals(message)) {
                isNeedGetCart = true;
                reFreshData();
                EventBus.getDefault().removeStickyEvent(message);
            }
            // 取消掉Loading框
            else if (Constants.EVENT_BUS_DISSMISS_DIALOG.equals(message)) {
                hidePopupWindow();
                if (mPlusMinusIcon != null) {
                    mPlusMinusIcon.setButtonCanClick(true);
                }
                EventBus.getDefault().removeStickyEvent(message);
            }
            // Gone掉购物车旁边的description
//            else if (Constants.EVENT_BUS_UPDATE_DESCRIPTION.equals(message)) {
//                UiUtils.updateCartDescription(getActivity(), Constants.PageType.CATEGORY);
//                EventBus.getDefault().removeStickyEvent(message);
//            }
        }
    }

    /**
     * 处理首页的定位显示问题
     * @param message
     */
    public void onEventMainThread(HomeDataLocatedStatus message) {
        if(message != null) {
            if (Constants.LocatedType.LOCATED_START.equals(message.getStatus())) {
                showDialog("定位中", false);
            } else if (Constants.LocatedType.LOCATED_SUCCESS.equals(message.getStatus())) {
                fetchData();
                hideDialog();
            } else if (Constants.LocatedType.LOCATED_FAILED.equals(message.getStatus())) {
                showLocatingFailedUi();
                hideDialog();
            }
            EventBus.getDefault().removeStickyEvent(message);
        }
    }

    // 发起商品 + / - 的请求
    public void onEventMainThread(PlusMinusIconMessage message) {
        if (message != null) {
            // 判断是否为没登陆购买
            if (message.message != null && message.message.contains("/IsFisrt")
                    && message.message.contains(Constants.STATE_HOMEFRAGMENT_BUTTON_BROADCAST)) {
                mPlusMinusIconMessage = message;
                if(message.icon != null && message.icon.mGoodsItem != null) {
                    mCurrentGoodsItemId = message.icon.mGoodsItem.id;
                }
                //提示首页刷新数据
                if (isAdded()) ((YMXMainActivity)getActivity()).isHomeFlush = true;
                isNeedGetCart = true;
                reFreshData();
                return;
            }
            // 正常购买
            mPlusMinusIcon = message.icon;
            if (message.message != null
                    && message.message.equals(Constants.STATE_HOMEFRAGMENT_BUTTON_BROADCAST)) {
                dealPlusMinusProtocol();
            }
        }
    }
}
